package com.zdft.promotion.common.distributelock;

import com.zdft.promotion.common.service.BusinessException;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class LockWorker {
    private final static String LOCKER_PREFIX = "lock:";

    private Logger logger = LoggerFactory.getLogger(LockWorker.class);

    @Autowired
    RedissonClient redissonClient;

    public <T> T lock(String resourceName, LockWorkerApi<T> worker) throws Exception {
        return lock(resourceName, worker, 200);
    }

    public <T> T lock(String resourceName, LockWorkerApi<T> worker, int lockTime) throws Exception {
        RLock lock = redissonClient.getLock(LOCKER_PREFIX + resourceName);
        // Wait for 300 seconds seconds and automatically unlock it after lockTime seconds
        boolean success = lock.tryLock(200, lockTime, TimeUnit.SECONDS);
        if (success) {
            try {
                return worker.lockWorker();
            } finally {
                lock.unlock();
            }
        }
        throw new BusinessException("10");
    }
}
